package cn.itcast.controller.system;

import cn.itcast.controller.BaseContorller;

import cn.itcast.domain.system.Dept;
import cn.itcast.service.system.DeptService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/system/dept")
public class DeptController extends BaseContorller {

    @Autowired
    private DeptService deptService;



    @RequestMapping(value = "/list",name = "分页展示部门数据显示")
    public String findAll(@RequestParam(value = "page",defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "5") Integer pageSize){
        PageInfo pageInfo =deptService.findPage(getCompanyId(),pageNum,pageSize);
        request.setAttribute("page",pageInfo);
        return "system/dept/dept-list";
    }

    @RequestMapping(value = "/toAdd",name = "跳转添加部门")
    public String toAdd(){
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);
        return "system/dept/dept-add";
    }


    @RequestMapping(value = "/edit",name = "保存部门")
    public String edit(Dept dept){
        if (dept.getParent().getId().equals("")){
            dept.getParent().setId(null);
        }

        if (StringUtils.isEmpty(dept.getId())){//id为空
            dept.setId(UUID.randomUUID().toString());
            dept.setCompanyId(getCompanyId());
            dept.setCompanyName(getCompanyName());
            deptService.save(dept);

        }else {//id不为空
            deptService.update(dept);
        }


        return "redirect:/system/dept/list.do";
    }

    @RequestMapping(value = "/toUpdate",name = "进入部门修改页面")
    public String update(String id){
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);
        Dept dept = deptService.findById(id);
        request.setAttribute("dept",dept);
        return "system/dept/dept-add";
    }

    @RequestMapping(value = "/delete",name = "进入部门修改页面")
    public String delete(String id){

        deptService.deleteById(id);

        return "redirect:/system/dept/list.do";
    }


}
